package binarysearch.在排序数组中查找元素的第一个和最后一个位置;

public class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] ans = new int[]{-1, -1};
        int search = search(nums, 0, nums.length - 1, target);
        if (search == - 1 ) {
            return ans ;
        }
        for (int i = 0;  search + i < nums.length || search - i > -1;i++) {
            if ( search - i > -1 && nums[ search - i ] == target ){
                ans[0] = search - i;
            }
            if (search + i < nums.length && nums[ search + i ] == target ){
                ans[1] = search + i;
            }
        }
        return ans;
    }

    int search(int[] nums, int start, int end, int target) {
        if (start > end) {
            return -1;
        }
        if (nums[(start + end) / 2] == target) {
            return (start + end) / 2;
        } else if (nums[(start + end) / 2] > target) {
            return search(nums, start, (start + end) / 2 - 1, target);
        } else {
            return search(nums, (start + end) / 2 + 1, end, target);
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] ints = solution.searchRange(new int[]{5,7,7,8,8,10}, 6);
        System.out.println(ints);
    }
}
